import React, { useEffect, useState } from 'react'

// 封装，fn数据发生变化是时，要回调的函数
export const useRequest = (fn, dependencies, defaultValue=[]) => {
    const [data,setDate]=useState(defaultValue);
    const [loading,setLoading]=useState(false);
    const [error,setError]=useState(false);

    const request=()=>{
        let cancel=false; // 取消
        setLoading(true);
        fn()
        .then(res=>{
            if(!cancel){
                setDate(res);
            }else{
                const {tab}=res;
                console.log(`request with ${tab} cancled`);
            }
        })
        .catch(()=>{
            if(!cancel){
                setError(error)
            }
        })
        .finally(()=>{
            if(!cancel){
                setLoading(false);
            }
        })
        return ()=>{
            cancel:true
        }
    }

    useEffect(()=>{
        const cancelRequest=request();
        // 卸载时执行
        return ()=>{
            cancelRequest();
        }
    },dependencies)

    return {data,setDate,loading,error,request}
}
